from datetime import datetime

from kubernetes import client, config


class KubernetesClient:
    def __init__(self, config_file):
        '''
        :param config_file: k8s kubeconfig
        '''
        self.config_file = config_file
        self.api_core_instance = None
        self.api_app_instance = None

    def load_config(self):
        '''
        加载kubeconfig认证文件
        :return: load k8s kubeconfig
        '''
        config.load_kube_config(config_file=self.config_file)
        self.api_core_instance = client.CoreV1Api()
        self.api_app_instance = client.AppsV1Api()

    def delete_pod(self, name, namespace="my-service"):
        '''
        删除pod
        :param name: pod_name
        :param namespace: namespace
        :return:
        '''
        api_response = self.api_core_instance.delete_namespaced_pod(name, namespace)
        return api_response

    def get_deployment_names(self, namespace):
        '''
        获取deployment名
        :param namespace: namespace
        :return: deployment_names list
        '''
        deployment = self.api_app_instance.list_namespaced_deployment(namespace)
        deployment_names = [deployment.metadata.name for deployment in deployment.items]
        return deployment_names

    def auto_scale_service(self, deployment_name, namespace, body):
        '''
        扩缩服务副本数
        :param deployment_name:
        :param namespace:
        :param body:
        :return:
        '''
        api_response = self.api_app_instance.patch_namespaced_deployment_scale(
            name=deployment_name,
            namespace=namespace,
            body=body
        )
        return api_response

    def rollout_restart_deployment(self, deployment_name, namespace):
        '''
        滚动重启服务
        :param deployment_name: deployment 名称
        :param namespace: 命名空间
        :return: API响应
        '''
        body = {"spec": {"template": {"metadata": {"annotations": {"kubectl.kubernetes.io/restartedAt": datetime.utcnow().isoformat()}}}}}
        api_response = self.api_app_instance.patch_namespaced_deployment(
            name=deployment_name,
            namespace=namespace,
            body=body
        )
        return api_response